#include "head.h"
#include "replace.h"
#include "rep.h"

int replace(struct Node* pn, char* find, char* rep)
{
	struct Node* currentr2, * currentc2;
	int p, i, k, x, y;
	int* cp;
	char c[25];
	char* cc = c;
	char* temp;
	free(pos);
	pos = malloc(40 * sizeof(int));
	for (i = 1; i <= 40; i++)
	{
		pos[i - 1] = -1;
	}
	cp = pos;
	i = 1;
	for (currentc2 = pn; currentc2->next != NULL && i <= 19; currentc2 = currentc2->next)
	{
		for (currentr2 = currentc2->data.cnode; currentr2->next != NULL; currentr2 = currentr2->next)
		{
			*cc = currentr2->data.rnode[1];
			cc++;
		}
		*cc = currentr2->data.rnode[1];
		*cc++;
		*cc = '\0';
		temp = strstr(c, find);
		if (temp != NULL)
		{
			*cp = i;
			cp++;
			*cp = strlen(c) - strlen(temp) + 1;
			cp++;
		}
		else
		{
			cp++;
			cp++;
		}
		i++;
		cc = c;
	}
	for (currentr2 = currentc2->data.cnode; currentr2->next != NULL; currentr2 = currentr2->next)
	{
		*cc = currentr2->data.rnode[1];
		cc++;
	}
	*cc = currentr2->data.rnode[1];
	*cc++;
	*cc = '\0';
	temp = strstr(c, find);
	*cp = i;
	cp++;
	if (temp != NULL)
	{
		*cp = strlen(c) - strlen(temp) + 1;
	}
	if (rep[0] == '\0')
	{
		return;
	}
	else
	{
		cp = pos;		
		for (i = 1; i <= 20; i++)
		{
			y = cp[2 * i - 2];
			x = cp[2 * i - 1];
			if (y > 0 && x > 0)
			{
				repl(pn, x, y, strlen(find), rep);
			}
		}
		return;
	}
}